import React,{useState,useEffect} from 'react'
import {Form,DatePicker,Input,Collapse,Select,Space,Button,Upload} from 'antd'
import { MinusCircleOutlined,PlusOutlined,LoadingOutlined} from '@ant-design/icons'
import { Url } from '@/Utils/services/url'
import moment from "moment";
export default function vote(props:any) {
  const [formData,setFormData]:any = useState({})
  const [loading,setLoading] = useState(false)
  const [imageUrl,setImageUrl] = useState('')
  const [form] = Form.useForm()
  const { Panel } = Collapse;
  const {RangePicker} = DatePicker
  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  }
  const options = [
    {
      value:1,
      label:'只可投一次'
    },
    {
      value:2,
      label:'每日均可投'
    }
  ]
  useEffect(()=>{
    if(props.formData.activityBasicId){
      let items = props.formData.activityVOS.filter((res:any) =>res.activityType === 2)
        setFormData({...items[0]})
      } else {
        setFormData(props.formData)
      }
  },[props.formData])
  useEffect(()=>{
    if(formData.startDate !==undefined){
      let time = []
      time.push(moment(formData.startDate))
      time.push(moment(formData.endDate))
      console.log('投票的时间：',time)
      let voteVos = []
      for(let item in formData.voteObjectVOS){
        let picture = [{
          key:formData.voteObjectVOS[item].pictureKey,
          value:formData.voteObjectVOS[item].pictureUrl,
          url:formData.voteObjectVOS[item].pictureUrl
        }]
        voteVos.push({name:formData.voteObjectVOS[item].name,instructions:formData.voteObjectVOS[item].instructions,picture:picture})
      }
      form.setFieldsValue({
        activityTime:time,
        voteWay:formData.voteWay,
        dayVoteLimit:formData.dayVoteLimit,
        singlePlayerLimit:formData.singlePlayerLimit,
        voteObjectVOS:[...voteVos]
      })
    }
  },[formData])
  useEffect(()=>{
    form.validateFields().then(res =>{
      if(props.form == true){
        let obj = {
          ...form.getFieldsValue(true),
          activityType:2
        }
        obj.startDate = obj.activityTime[0].format('YYYY-MM-DD hh:mm:ss')
        obj.endDate = obj.activityTime[1].format('YYYY-MM-DD hh:mm:ss')
        if(obj.voteObjectVOS){
          for(let item in obj.voteObjectVOS){
              if(obj.voteObjectVOS[item].picture &&formData.id == undefined){
                obj.voteObjectVOS[item].pictureUrl = obj.voteObjectVOS[item].picture[0].response.data.imgUrl
                obj.voteObjectVOS[item].pictureKey = obj.voteObjectVOS[item].picture[0].response.data.imgKey
                delete obj.voteObjectVOS[item].picture
              } else {
                obj.voteObjectVOS[item].pictureUrl = obj.voteObjectVOS[item].picture[0].value
                obj.voteObjectVOS[item].pictureKey = obj.voteObjectVOS[item].picture[0].key
                delete obj.voteObjectVOS[item].picture
              }
          }
        }
        let toDataObj = {
          activityType:2,
          startDate:obj.startDate,
          endDate:obj.endDate,
          voteWay:obj.voteWay,
          dayVoteLimit:obj.dayVoteLimit?obj.dayVoteLimit : 99999999,
          singlePlayerLimit:obj.singlePlayerLimit?obj.singlePlayerLimit : 99999999,
          voteObjectVOS:obj.voteObjectVOS
        }
        props.voteForm(toDataObj)
      }
    })
    
  },[props.form])
  function normFile(e: any){
    let url = e.file.status == 'done'?e.file.response.data.imgUrl:''
    setImageUrl(url)
    return e?.fileList;
};
const uploadButton = (
  <div>
    {loading ? <LoadingOutlined /> : <PlusOutlined />}
    <div style={{ marginTop: 8 }}>Upload</div>
  </div>
)
  return (
    <div>
        <Collapse  collapsible="header" defaultActiveKey={['1']}>
              <Panel header='投票' key="1">
                <Form
                        form={form}
                        name="validate_other"
                        layout="horizontal"
                        {...formItemLayout}
                    >
                        <Form.Item
                        >
                            <span>基本信息</span>
                                  <Form.Item
                                    name="activityTime"
                                    label="活动时间"
                                    rules={[{ required: true }]}
                                >
                                    <RangePicker/>
                                </Form.Item>
                                <Form.Item
                                    name="voteWay"
                                    label="投票方式"
                                >
                                    <Select options={options}></Select>
                                </Form.Item>
                                <Form.Item
                                    noStyle
                                   shouldUpdate={(prevValues, currentValues) => prevValues.voteWay !== currentValues.voteWay}
                                >
                                    {({ getFieldValue }) =>
                                        getFieldValue('voteWay') === 2 ? (
                                          <Form.Item
                                              name="dayVoteLimit"
                                              label="单日可投上限"
                                              rules={[{ required: true }]}
                                            
                                          >
                                            <Input type="number"></Input>
                                          </Form.Item>
                                        ) : null
                                    }
                                   
                                </Form.Item>
                                <Form.Item
                                    noStyle
                                   shouldUpdate={(prevValues, currentValues) => prevValues.voteWay !== currentValues.voteWay}
                                >
                                    {({ getFieldValue }) =>
                                        getFieldValue('voteWay') === 2 ? (
                                          <Form.Item
                                              name="singlePlayerLimit"
                                              label="重复投票上限"
                                              rules={[{ required: true }]}
                                            
                                          >
                                            <Input type="number"></Input>
                                          </Form.Item>
                                        ) : null
                                    }
                                   
                                </Form.Item>
                        </Form.Item>
                        <Form.Item
                          noStyle
                        >
                           <span>投票对象</span>
                            <Form.List name="voteObjectVOS">
                              {(fields, { add, remove }) => (
                                <>
                                  {fields.map(({ key, name, ...restField }) => (
                                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                      <Form.Item
                                        noStyle
                                      >
                                          <Form.Item
                                            label="姓名"
                                            {...restField}
                                            name={[name, 'name']}
                                            rules={[{ required: true, message: '请输入投票对象名称' }]}
                                          >
                                            <Input placeholder="请输入投票对象的名称" />
                                          </Form.Item>
                                          <Form.Item
                                            label="说明"
                                            {...restField}
                                            name={[name, 'instructions']}
                                            rules={[{ required: true, message: '请输入投票对象的说明' }]}
                                          >
                                            <Input placeholder="请输入投票对象的说明" />
                                          </Form.Item>
                                      </Form.Item>
                                      <Form.Item
                                         label="图片"
                                        {...restField}
                                        valuePropName="fileList"
                                        getValueFromEvent={normFile}
                                        name={[name, 'picture']}
                                        rules={[{ required: true, message: '请上传图片' }]}
                                      >
                                       <Upload
                                          name="multipartFile"
                                          listType="picture-card"
                                          className="avatar-uploader"
                                          action={`/campus/campusweb/${Url.upLoad}`}
                                        >
                                          {uploadButton}
                                        </Upload>
                                        
                                      </Form.Item>
                                      <MinusCircleOutlined onClick={() => remove(name)} />
                                    </Space>
                                  ))}
                                  <Form.Item>
                                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                      添加
                                    </Button>
                                  </Form.Item>
                                </>
                              )}
                            </Form.List>
                        </Form.Item>
                    </Form>
              </Panel>
           </Collapse>
    </div>
  )
}
